package com.atguigu.gulimall.sso.client.controller;

import com.atguigu.common.constant.AuthServerConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;

@Controller
public class HelloController {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 无需登录就能访问
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/employee")
    public String employee(@RequestParam(required = false) String token, Model model, HttpSession session, HttpServletRequest request) {
        //todo 过滤器 切面 单点登录
        if (!StringUtils.isEmpty(token)) {
            Object loginUser = redisTemplate.opsForValue().get(token);
            if (loginUser != null) {
                session.setAttribute(AuthServerConstant.LOGIN_USER, loginUser);
            }
        }
        Object loginUser = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (loginUser != null) {

            System.out.println(token + ":" + loginUser);
            ArrayList<String> employee = new ArrayList<>();
            employee.add("张三");
            employee.add("李四");
            model.addAttribute("employee", employee);
            return "employee";

        }
        return "redirect:http://server.com:8081/loginPage?redirectUrl=" + request.getRequestURL().toString();
    }
}
